package com.daka.service.impl;

import com.daka.dao.UserMapper;
import com.daka.entity.Organization;
import com.daka.entity.User;
import com.daka.enumerate.CommonStatus;
import com.daka.enumerate.StatusCode;
import com.daka.service.OrganizationService;
import com.daka.service.UserService;
import com.daka.tools.MD5Util;
import com.daka.tools.rongYun.RongCloudSMS;
import com.daka.vo.response.DataResponseVo;
import com.daka.vo.response.user.UserDetailVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author beliveli on 2016/3/31 0031.
 */
@Service("userService")
@SuppressWarnings("unused")
public class UserServiceImpl implements UserService {

    @Resource(name = "userMapper")
    private UserMapper userMapper;

    @Resource(name = "redisClient")
    private RedisClient redisClient;

    @Resource
    private OrganizationService organizationService;


    public User selectByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    public User selectById(int manageId) {
        return userMapper.selectById(manageId);
    }

    public int updatePasswordById(User user) {
        return userMapper.updatePasswordById(user);
    }

    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    public List<User> selectAllByOrgId(int orgId) {
        return userMapper.selectAll();
    }

    public List<User> selectByOrgId(int orgId) {
        return userMapper.selectByOrgId(orgId);
    }

    public List<User> selectPageByOrgId(Integer orgId, String userName, Integer pageIndex, Integer pageSize) {
        return userMapper.selectPageByOrgId(orgId, userName, pageIndex, pageSize);
    }

    public int selectCountByOrgId(Integer orgId, String userName) {
        return userMapper.selectCountByOrgId(orgId, userName);
    }

    public DataResponseVo<UserDetailVo> login(User userParam) {
        User user = userMapper.selectByPhone(userParam.getPhone());

        if (user == null) {
            return new DataResponseVo<>(StatusCode.NOT_LOGIN.getStatusCode(), "user not exists");
        }

        if(user.getStatus() == CommonStatus.DISABLED.getStatusCode()){
            return new DataResponseVo<>(StatusCode.USER_LOCKED.getStatusCode(), StatusCode.USER_LOCKED.getStatusMessage());
        }

        if (user.getPassword().equalsIgnoreCase(MD5Util.MD5(userParam.getPassword()))) {

            Organization organization = organizationService.selectById(user.getOrgId());

            if(organization.getStatus() == CommonStatus.DISABLED.getStatusCode()){
                return new DataResponseVo<>(StatusCode.ORG_LOCKED.getStatusCode(), StatusCode.ORG_LOCKED.getStatusMessage());
            }

            return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), "", UserDetailVo.build(user, organization));
        } else {
            return new DataResponseVo<>(StatusCode.SELECT_ITEM_NOT_EXISTS.getStatusCode(), "Username password do not match");
        }
    }

    public User updateOrgIdById(Integer orgId, Integer userId) {
        userMapper.updateOrgIdById(orgId, userId);
        return userMapper.selectById(userId);
    }

    public User updateStatus(Integer userId) {

        User result = userMapper.selectById(userId);

        if (result == null) {
            return null;
        }

        int resultCount;
        if (result.getStatus() == CommonStatus.NORMAL.getStatusCode()) {
            result.setStatus(CommonStatus.DISABLED.getStatusCode());
            resultCount = userMapper.updateStatus(CommonStatus.DISABLED.getStatusCode(), userId);
        } else {
            result.setStatus(CommonStatus.NORMAL.getStatusCode());
            resultCount = userMapper.updateStatus(CommonStatus.NORMAL.getStatusCode(), userId);
        }

        if (resultCount == 0) {
            return null;
        }

        return result;
    }

    public User save(User userParam) {

        int resultCount;
        User user;
        if (userParam.getUserId() == 0) {
            userParam.setCreateTime(new Timestamp(new Date().getTime()));
            userParam.setStatus(CommonStatus.NORMAL.getStatusCode());
            userParam.setPassword(MD5Util.MD5(userParam.getPassword()));

            resultCount = userMapper.saveUser(userParam);
        } else {
            resultCount = userMapper.updateById(userParam);
        }

        if (resultCount == 0) {
            return null;
        }
        return userParam;
    }

    public String sendVerifierCode(String mobile){
        String randCode = "";
        try{
            randCode = RongCloudSMS.sendCode(mobile);
            System.out.println(randCode);
            redisClient.set("resetPassword",mobile, randCode);
            redisClient.expire(mobile, 60);
        } catch (Exception e){
            e.printStackTrace();
        }
        return randCode;
    }

    public Boolean checkVerifierCode(String mobile,String code){
        try
        {
            String redisCode = (String)redisClient.get("resetPassword", mobile,String.class);
            if(redisCode != null && code.equals(redisCode)){
                redisClient.remove("resetPassword", mobile);
                return true;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    private static String get4Rand()
    {
        Random rand = new Random();
        int tmp = Math.abs(rand.nextInt());
        return String.valueOf(tmp % (9999 - 1000 + 1) + 1000);
    }
}
